package com.ebt.m.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.webkit.JavascriptInterface;
import android.widget.Toast;

import com.ebt.m.AppContext;
import com.ebt.m.R;
import com.ebt.m.activity.MainActivity;
import com.ebt.m.activity.WebBaseActivity;
import com.ebt.m.data.bean.CardInfo;
import com.ebt.m.event.SyncCardEvent;
import com.ebt.m.share.ShareDialog;
import com.ebt.m.utils.ConfigData;
import com.ebt.m.utils.TalkingDataUtil;
import com.ebt.m.utils.js.JsObject;
import com.ebt.m.utils.netstatus.NetChangedEvent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * 我的公司
 *
 * @author Andy.Wang
 */
public class CompanyFragment extends WebBaseFragment {
    private Menu menu;
    private final String jsInterface = "EbtJsBridge";
    private JsObject jsObject = null;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        super.onCreateOptionsMenu(menu, inflater);
        inflater.inflate(R.menu.menu_company, menu);
        this.menu = menu;
    }


    protected String createUrl() {
        return link;
    }

    @Override
    protected void setJSInterface() {
        mWebView.addJavascriptInterface(new JSObj(), "jsObj");
        mWebView.addJavascriptInterface(jsObject = new JsObject(getContext()), jsInterface);
    }

    public class JSObj {

        @JavascriptInterface
        public void syncCard() {
        }

        @JavascriptInterface
        public void gotoEditPage() {
            gotoEdit();
        }

        @JavascriptInterface
        public String getLocationStr(double longitude, double latitude) {
            return null;
        }

        @JavascriptInterface
        public void setTitle(String title) {
            ToolbarEvent toolbarEvent = new ToolbarEvent();
            toolbarEvent.eventType = 0;
            toolbarEvent.title = title;
            EventBus.getDefault().post(toolbarEvent);
        }

        @JavascriptInterface
        public void showMenu(boolean isShow) {
            ToolbarEvent toolbarEvent = new ToolbarEvent();
            toolbarEvent.eventType = 1;
            toolbarEvent.showMenu = isShow;
            EventBus.getDefault().post(toolbarEvent);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventToolbarChanged(ToolbarEvent event) {
        if (event.eventType == 0) {
            ((WebBaseActivity) getActivity()).setTitle(event.title);
        } else if (event.eventType == 1) {
            for (int i = 0; i < menu.size(); i++) {
                menu.getItem(i).setVisible(event.showMenu);
                menu.getItem(i).setEnabled(event.showMenu);
            }
        }
    }

    public class ToolbarEvent {
        public int eventType;
        public String title;
        public boolean showMenu;
    }

    private void gotoEdit() {
        TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_EDIT_CARD);
        if (jsObject == null) {
            return;
        }
        String cardUrl = (String) jsObject.getResultMap().get("editCardUrl");
        if (cardUrl != null && cardUrl.length() > 0) {
            Intent cloudIntent = new Intent(getActivity(), WebBaseActivity.class);
            Bundle bundle = new Bundle();
            bundle.putString(WebBaseActivity.WEB_TYPE_TITLE, "名片编辑");
            bundle.putInt(WebBaseActivity.WEB_TYPE_FRAGMENT, WebBaseActivity.FRAGMENT_4OLD_BASE);
            bundle.putString(WebBaseActivity.WEB_TYPE_LINK, cardUrl);
            cloudIntent.putExtras(bundle);
            startActivity(cloudIntent);
        }
    }

    private void showShareDialog() {
        CardInfo cardInfo = AppContext.getCurrentUser().getCardInfo();
        if (TextUtils.isEmpty(cardInfo.getName())) {
            Toast.makeText(getActivity(), "名片数据缺失", Toast.LENGTH_SHORT).show();
            return;
        }
        Activity activity = getActivity();
        boolean hasShareListeners = false;
        if (activity instanceof MainActivity) {
            hasShareListeners = true;
        }
        String shareUrl = (String) jsObject.getResultMap().get("shareUrl");
        if (shareUrl != null && shareUrl.length() > 0) {
            List<String> hideList = new ArrayList<>();
            hideList.add(ShareDialog.COPY_LINK);
            new ShareDialog.Builder(getActivity())
                    .setShareTitle(cardInfo.getName() + "的个人名片")
                    .setShareContent("您好，我是保险顾问" + cardInfo.getName() + "，愿竭诚为您服务！")
                    .setShareUrl(shareUrl)
                    .setHidePlatformList(hideList)
                    .setShareImagePath(ConfigData.PORTRAITPATH + File.separator + "card.png")
                    .setShareListener(hasShareListeners ? ((MainActivity) activity).getShareListener() : null)
                    .setDialogDismissIfShareSuccess()
                    .create()
                    .show();
        }
        TalkingDataUtil.onEvent(TalkingDataUtil.TYPE_SHARE_CARD);
    }

    /**
     * 名片更新回调
     *
     * @param event
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(SyncCardEvent event) {
        if (!event.fromLogin) {
            loadData();
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int itemId = item.getItemId();
        switch (itemId) {
            case android.R.id.home:
                getActivity().finish();
                break;
            case R.id.action_edit:
                gotoEdit();
                break;
            case R.id.action_share:
                showShareDialog();
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (mWebView != null) {
            mWebView.destroy();
        }
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventNetChanged(NetChangedEvent event) {
        if (event.onNetConnected) {
            loadData();
        }
    }

}
